package com.heima.wemedia.service.impl;

import com.heima.apis.schedule.TaskFeignClient;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoPublishService;
import com.heima.wemedia.service.WmNewsCheckService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class WmNewsAutoPublishServiceImpl implements WmNewsAutoPublishService {
    @Autowired
    private TaskFeignClient taskFeignClient;
    @Autowired
    private WmNewsCheckService wmNewsCheckService;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    //拉起任务，消费后发布
    @Override
    @Scheduled(cron = "0/30 * * * * ?")
    public void autoPublish() {
        //1.调用远程微服务拉取任务
        //1.1获取任务进行消费
        ResponseResult<Task> responseResult = taskFeignClient.consumerTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //1.2判断任务是否存在
        if (responseResult.getCode()!=200 || responseResult.getData() == null){
            //不存在
            return;
        }
        //2.调用文章微服务保存数据
        //2.1从拉取任务消费的结果中或获取该任务对象
        Task task = responseResult.getData();
        //2.2从task从获取字节数组并转为对象,获取封装在其中的文章id，并通过id查询文章详情
        WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
        wmNews = wmNewsMapper.selectById(wmNews.getId());
        //2.3判断文章是存在
        if (wmNews == null){
            return;
        }
        //2.4存在，则调用将自媒体文章保存到App端中Article数据库中
        ResponseResult<Long> longResponseResult = wmNewsCheckService.saveWmNewsToArticle(wmNews);
        if (longResponseResult.getCode()!=200){
            throw new RuntimeException("调用远程文章服务出现异常：" + longResponseResult.getErrorMessage());
        }

        //2.5发布成功，修改自媒体文章在数据库中的数据
        wmNews.setArticleId(longResponseResult.getData());
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setReason("文章发布成功！");
        wmNewsMapper.updateById(wmNews);
    }
}
